package net.bblbs.zhongrx;

import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.bblbs.zhongrx.db.Person;
import net.bblbs.zhongrx.util.AttachEnum;
import net.bblbs.zhongrx.util.HttpCallbackListener;
import net.bblbs.zhongrx.util.HttpRequest;
import net.bblbs.zhongrx.util.StateEnum;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class SelectActivity extends BaseActivity implements SearchView.OnQueryTextListener {

    private static final String TAG = "ZRX_SELECT_ACTIVITY";
    private static final String ALBUM_NAME = "ZRX";

    private Button btn_select;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeContainer;
    private DrawerLayout mDrawerLayout;

    private TextView mTVUsername;

    DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);

        View header=navView.getHeaderView(0);
        mTVUsername = (TextView)header.findViewById(R.id.username);
        SharedPreferences sp = this.getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
        String email = sp.getString("email","");
        mTVUsername.setText(email);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_logoff:
                        mDrawerLayout.closeDrawers();
                        SharedPreferences sp = SelectActivity.this.getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
                        sp.edit().putString("password","").commit();
                        finish();
                        Intent intent = new Intent(SelectActivity.this, LoginActivity.class);
                        startActivity(intent);
                        break;

                    default:
                        break;
                }

                return true;
            }
        });


        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_person);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        recyclerView.setLayoutManager(layoutManager);


        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override

            public void onRefresh() {

                // Your code to refresh the list here.

                // Make sure you call swipeContainer.setRefreshing(false)

                // once the network request has completed successfully.

                Log.d(TAG, "on refresh");
                getPersonList(null);

            }

        });

        getPersonList(null);

    }

    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode) {
            case 1:
                if(resultCode == RESULT_OK) {
                    getPersonList(null);
                }
                break;
            default:
                break;
        }

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        getPersonList(query);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        getPersonList(newText);
        return false;
    }

    public void getPersonList(String queryText){
        String apiPath = "/tango/listAddtionalDataPendingRecords/100/0";

        if (TextUtils.isEmpty(queryText)){

        }else{
            apiPath += "/" + queryText;
        }

        HttpRequest.getWithCallback(getString(R.string.ws_base_url), apiPath,new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                final String personInfo = response;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        JSONArray jsonObjContent = null;
                        List<Person> list = new ArrayList<Person>();
                        try {
                            jsonObjContent = new JSONObject(personInfo).getJSONObject("data").getJSONArray("content");

                            for (int i = 0 ; i < jsonObjContent.length(); i++){
                                JSONObject obj = (JSONObject)jsonObjContent.get(i);
                                String id = obj.getString("id");
                                Date cDate = (new Date( new Long(obj.getString("createdDate"))));
                                String createdDate = sdf.format(cDate);

                                String basicData = obj.getJSONObject("basicData").toString();
                                String additionalData ="";
                                String paymentInfo ="";

                                if (obj.has("addtionalData") && ! obj.isNull("addtionalData")){
                                    additionalData =obj.getJSONObject("addtionalData").toString();
                                }

                                if (obj.has("paymentInfo") && ! obj.isNull("paymentInfo")){
                                    paymentInfo =obj.getJSONObject("paymentInfo").toString();
                                }

                                String name = "";
                                try{
                                    name = obj.getJSONObject("basicData").getString("融资人");
                                }catch (Exception e){
                                    continue;
                                }

                                String mobile = "";
                                try {
                                    mobile = obj.getJSONObject("basicData").getString("手机号");
                                }catch (Exception e){

                                }

                                String idNo = "";
                                try {
                                    idNo = obj.getJSONObject("basicData").getString("身份证号");
                                }catch (Exception e){

                                }


                                String state = obj.getString("state");
                                String comment = obj.getString("comment");
                                if (comment ==null || comment.equals("null")) {
                                    comment = "";
                                }

//                                String idCardFrontImg="";
//                                String idCardBackImg="";
//                                String resident1stImg="";
//                                String resident2ndImg="";
//
//                                String resident3rdImg="";
//                                String resident4thImg="";
//                                String maritalImg="";
//                                String housePropImg="";
//
//                                String earningImg="";
//                                String districtImg="";
//                                String buildingImg="";
//                                String buildingNoImg = "";
//
//                                String houseNoImg="";
//                                String indoorImg="";
//                                String groupImg="";

                                String installmentVid="";
                                String guaranteeVid="";
                                String mortgageVid="";
                                String commitmentVid="";

                                if (obj.has("attachments") && ! obj.isNull("attachments")) {
                                    JSONObject attach = obj.getJSONObject("attachments");
                                    if (attach != null) {

                                        if (attach.has(AttachEnum.INSTALLMENT_VID.getValue())){
                                            installmentVid = attach.getString(AttachEnum.INSTALLMENT_VID.getValue());
                                        }

                                        if (attach.has(AttachEnum.GUARANTEE_CONTRACT_VID.getValue())){
                                            guaranteeVid = attach.getString(AttachEnum.GUARANTEE_CONTRACT_VID.getValue());
                                        }

                                        if (attach.has(AttachEnum.MORTGAGE_CONTRACT_VID.getValue())){
                                            mortgageVid = attach.getString(AttachEnum.MORTGAGE_CONTRACT_VID.getValue());
                                        }

                                        if (attach.has(AttachEnum.COMMITMENT_LETTER_VID.getValue())){
                                            commitmentVid = attach.getString(AttachEnum.COMMITMENT_LETTER_VID.getValue());
                                        }
                                    }
                                }
                                Person person = new Person(
                                      id
                                    , name
                                    , mobile
                                    , idNo
                                    , state
                                    , comment
                                    , createdDate
                                    , installmentVid
                                    , guaranteeVid
                                    , mortgageVid
                                    , commitmentVid
                                    , basicData
                                    , additionalData
                                    , paymentInfo
                                );
                                list.add(person);
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "JSONException"+ e.toString() );
                        }

                        Log.d(TAG, "print PhaseJSON: " +personInfo);

                        PersonAdapter adapter= new PersonAdapter(list);
                        recyclerView.setAdapter(adapter);
                        swipeContainer.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onError(Exception e) {
                swipeContainer.setRefreshing(false);
                Log.d(TAG, "onError: "+ e.toString());
            }
        });
    }



    class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolder>{

        private List<Person> mPersonList;

        class ViewHolder extends RecyclerView.ViewHolder {
            View personView;
            TextView personName;
            TextView personMobile;
            TextView personState;
            TextView personComment;
            TextView personCreatedDate;

            public ViewHolder(View view) {
                super(view);
                personView = view;
                personName = (TextView) view.findViewById(R.id.person_name);
                personMobile = (TextView) view.findViewById(R.id.person_mobile);
                personState = (TextView) view.findViewById(R.id.person_state);
                personComment = (TextView) view.findViewById(R.id.person_comment);
                personCreatedDate = (TextView) view.findViewById(R.id.person_createdDate);
            }
        }

        public PersonAdapter(List<Person> personList) {
            mPersonList = personList;
        }

        @Override
        public PersonAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.person_item, parent, false);
            final PersonAdapter.ViewHolder holder = new PersonAdapter.ViewHolder(view);
            holder.personView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getAdapterPosition();
                    Person person = mPersonList.get(position);
//                    Toast.makeText(v.getContext(), "you clicked view " + person.getMobile(), Toast.LENGTH_SHORT).show();
                    final Intent intent = new Intent(SelectActivity.this, SectionListActivity.class);
                    intent.putExtra("person_data", person);

                    String prevInstallmentVid="";
                    String prevGuaranteeVid="";
                    String prevMortgageVid="";
                    String prevCommitmentVid="";
                    String prevGuaranteeMateVid="";
                    String prevMortgageMateVid="";

//                    if (person.getState().equals(StateEnum.UPLOADING.getValue())
//                        || person.getState().equals(StateEnum.EXAM_SENDBACK.getValue())
//                        || person.getState().equals(StateEnum.TARCUSTOM.getValue())
//                        ) {
                        File fileDirectory = new File(SelectActivity.this.getExternalFilesDir(null), ALBUM_NAME + "/" + person.getId());
                        File[] dirFiles = fileDirectory.listFiles();

                        String fragment1Imgs = "";
                        String fragment2Imgs = "";
                        String fragment3Imgs = "";
                        String fragment4Imgs = "";

                        String dynImgs = "";
                        if (dirFiles != null && dirFiles.length != 0) {

                            for (int ii = 0; ii < dirFiles.length; ii++) {

                                //delete size 0 temp file
                                if (dirFiles[ii].length() == 0 && !(dirFiles[ii].getName().contains("nomedia"))) {
                                    dirFiles[ii].delete();
                                    continue;
                                }

                                String fileOutput = dirFiles[ii].toString();

                                if (fileOutput.contains("VID_" + AttachEnum.INSTALLMENT_VID.ordinal() + "_")) {
                                    prevInstallmentVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }

                                if (fileOutput.contains("VID_" + AttachEnum.GUARANTEE_CONTRACT_VID.ordinal() + "_")) {
                                    prevGuaranteeVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }

                                if (fileOutput.contains("VID_" + AttachEnum.MORTGAGE_CONTRACT_VID.ordinal() + "_")) {
                                    prevMortgageVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }

                                if (fileOutput.contains("VID_" + AttachEnum.COMMITMENT_LETTER_VID.ordinal() + "_")) {
                                    prevCommitmentVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }

                                if (fileOutput.contains("VID_" + AttachEnum.GUARANTEE_CONTRACT_MATE_VID.ordinal() + "_")) {
                                    prevGuaranteeMateVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }

                                if (fileOutput.contains("VID_" + AttachEnum.MORTGAGE_CONTRACT_MATE_VID.ordinal() + "_")) {
                                    prevMortgageMateVid = dirFiles[ii].getAbsolutePath();
                                    continue;
                                }


                                if (fileOutput.contains(Photo1Fragment.SP_NAME)){
                                    if (fragment1Imgs.equals("")){
                                        fragment1Imgs +=dirFiles[ii].getAbsolutePath();
                                    }else{
                                        fragment1Imgs += "|"+ dirFiles[ii].getAbsolutePath();
                                    }
                                }

                                if (fileOutput.contains(Photo2Fragment.SP_NAME)){
                                    if (fragment2Imgs.equals("")){
                                        fragment2Imgs +=dirFiles[ii].getAbsolutePath();
                                    }else{
                                        fragment2Imgs += "|"+ dirFiles[ii].getAbsolutePath();
                                    }
                                }

                                if (fileOutput.contains(Photo3Fragment.SP_NAME)){
                                    if (fragment3Imgs.equals("")){
                                        fragment3Imgs +=dirFiles[ii].getAbsolutePath();
                                    }else{
                                        fragment3Imgs += "|"+ dirFiles[ii].getAbsolutePath();
                                    }
                                }

                                if (fileOutput.contains(Photo4Fragment.SP_NAME)){
                                    if (fragment4Imgs.equals("")){
                                        fragment4Imgs +=dirFiles[ii].getAbsolutePath();
                                    }else{
                                        fragment4Imgs += "|"+ dirFiles[ii].getAbsolutePath();
                                    }
                                }


                                if (fileOutput.contains(DynamicPhotoFragment.SP_NAME)){
                                    if (dynImgs.equals("")){
                                        dynImgs +=dirFiles[ii].getAbsolutePath();
                                    }else{
                                        dynImgs += "|"+ dirFiles[ii].getAbsolutePath();
                                    }
                                }

                            }
                        }

                        String sortedFgmt1Names = getSortedImageNames(fragment1Imgs, Photo1Fragment.SP_NAME , person);
                        intent.putExtra(Photo1Fragment.SP_NAME, sortedFgmt1Names);

                        String sortedFgmt2Names = getSortedImageNames(fragment2Imgs, Photo2Fragment.SP_NAME , person);
                        intent.putExtra(Photo2Fragment.SP_NAME, sortedFgmt2Names);

                        String sortedFgmt3Names = getSortedImageNames(fragment3Imgs, Photo3Fragment.SP_NAME , person);
                        intent.putExtra(Photo3Fragment.SP_NAME, sortedFgmt3Names);

                        String sortedFgmt4Names = getSortedImageNames(fragment4Imgs, Photo4Fragment.SP_NAME , person);
                        intent.putExtra(Photo4Fragment.SP_NAME, sortedFgmt4Names);



                        String sortedImageNames = getSortedImageNames(dynImgs, DynamicPhotoFragment.SP_NAME, person);
                        intent.putExtra(DynamicPhotoFragment.SP_NAME, sortedImageNames);

                        intent.putExtra(AttachEnum.INSTALLMENT_VID.getValue(), prevInstallmentVid);
                        intent.putExtra(AttachEnum.GUARANTEE_CONTRACT_VID.getValue(), prevGuaranteeVid);
                        intent.putExtra(AttachEnum.MORTGAGE_CONTRACT_VID.getValue(), prevMortgageVid);
                        intent.putExtra(AttachEnum.COMMITMENT_LETTER_VID.getValue(), prevCommitmentVid);
                        intent.putExtra(AttachEnum.GUARANTEE_CONTRACT_MATE_VID.getValue(), prevGuaranteeMateVid);
                        intent.putExtra(AttachEnum.MORTGAGE_CONTRACT_MATE_VID.getValue(), prevMortgageMateVid);

//                    }
//                    else if (person.getState().equals(StateEnum.REVIEW_SENDBACK.getValue())){
//
//                        Log.d(TAG, "person: "+ person.toString());
//
//                        prevIdCardImg = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getIdCardImg();
//                        prevResidentImg = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getResidentImg();
//                        prevMaritalImg = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getMaritalImg();
//                        prevHouseImg = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getHouseImg();
//                        prevEarningImg = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getEarningImg();
//
//
//                        // todo other optional photo
////                        if TextUtils.isEmpty(person.)
//
//                        prevInstallmentVid = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getInstallmentVid();
//                        prevGuaranteeVid = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getGuaranteeVid();
//                        prevMortgageVid = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getMortgageVid();
//                        prevCommitmentVid = getString(R.string.ws_base_url)+ "/tango/getFile/"+ person.getCommitmentVid();
//
//                        intent.putExtra(AttachEnum.ID_CARD_IMG.getValue(), prevIdCardImg);
//                        intent.putExtra(AttachEnum.RESIDENCE_BOOKLET_IMG.getValue(), prevResidentImg);
//                        intent.putExtra(AttachEnum.MARITAL_STATUS_IMG.getValue(), prevMaritalImg);
//                        intent.putExtra(AttachEnum.HOUSE_PROPERTY_IMG.getValue(), prevHouseImg);
//                        intent.putExtra(AttachEnum.EARNING_IMG.getValue(), prevEarningImg);
//
//                        intent.putExtra(AttachEnum.INSTALLMENT_VID.getValue(), prevInstallmentVid);
//                        intent.putExtra(AttachEnum.GUARANTEE_CONTRACT_VID.getValue(), prevGuaranteeVid);
//                        intent.putExtra(AttachEnum.MORTGAGE_CONTRACT_VID.getValue(), prevMortgageVid);
//                        intent.putExtra(AttachEnum.COMMITMENT_LETTER_VID.getValue(), prevCommitmentVid);
//                    }
                    startActivityForResult(intent,1);
                }
            });

            return holder;
        }

        @Override
        public void onBindViewHolder(PersonAdapter.ViewHolder holder, int position) {
            Person person = mPersonList.get(position);
            holder.personMobile.setText(person.getMobile());
            holder.personName.setText(person.getName());
            holder.personState.setText(person.getState());
            holder.personComment.setText(person.getComment());
            holder.personCreatedDate.setText(person.getCreatedDate());
        }

        @Override
        public int getItemCount() {
            return mPersonList.size();
        }

        public String getSortedImageNames(String files, String spName, Person person ){
            SharedPreferences pref = SelectActivity.this.getSharedPreferences(spName, Context.MODE_PRIVATE);

            String names = pref.getString(spName + "_" + person.getId(),"");
            String[] nameArray = names.split("\\|", -1);
            int name_len = nameArray.length;
            String result ="";

            String[] fileArray = files.split("\\|", -1);
            int file_len = fileArray.length;
//            if ((file_len ==1) && files.equals("")){
//                return result;
//            }

            for(int i  = 0 ; i < name_len; i++){
                boolean hasPhotoAtI = false;
                for(int j = 0; j < file_len; j++){
                    if(fileArray[j].contains(spName+ "_" +i+"_")){
                        if ( i> 0){
                            result +=  "|" +fileArray[j];
                        }else{
                            result +=  fileArray[j];
                        }
                        hasPhotoAtI = true;
                    }
                }

                if (!hasPhotoAtI) {
                    if (i >0){
                        result += "|";
                    }
                }

            }
            return result;
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;

            default:
        }
        return true;
    }
}
